<?php
namespace App\Http\Controllers;

use Illuminate\Mail\Mailer;
use Illuminate\Http\Request;
use App\Http\Controllers\Common\ajaxReturnJsonContent;

class TextContoller extends Controller
{
    private $mailer;

    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }
    /**
     * 发送邮件
     */
    public function mail(Request $request)
    {
    	//判断请求是否为ajax
    	if (!$request->ajax()) {
    		return redirect('register');
    	}
    	//判断有无邮箱
    	if (!$request->email) {
    		return json_encode(ajaxReturnJsonContent::returnVal($request->email, 'success', 'Not Fount Email'));
    	}
        //存储验证码
    	$request->session()->put('code', $request->content);
        //测试数据
        $viewData = ['title' => '你若盛开，清风自来','author' => '木心'];
        $emailData = [
            'content' => $request->content,
            'subject' => '注册的验证码',//邮件主题
            'addr' => $request->email,//邮件接收地址
        ];
        //发送邮件
        $this->sendText($emailData);
        return json_encode(ajaxReturnJsonContent::returnVal(true, 'success', 'fail'));
        //$this->sendHtml('mail',$viewData,$emailData);
        //TODO  $tag 判断发送是否成功，进行后续代码开发
        
    }

    /**
     * 发送纯文本 邮件
     * @param $emailData 邮件数据
     */
    public function sendText($emailData){
        //此处为文本内容
        $tag = $this->mailer
            ->raw($emailData['content'],
                function ($message) use ($emailData){
                    $message->subject($emailData['subject']);
                    $message->to($emailData['addr']);
                });
        return $tag;
    }
    /**
     * 发送自定义网页
     * @param $emailData 邮件数据
     * @param $viewPage html视图
     * @param $viewData html传输数据
     */
    public function sendHtml($viewPage,$viewData,$emailData){
        $tag = $this->mailer
            ->send($viewPage,$viewData,
                function ($message) use ($emailData){
                    $message->subject($emailData['subject']);
                    $message->to($emailData['addr']);
                });
        return $tag;
    }
}